package com.jobs.core;

import java.util.HashMap;
import java.util.Map;

import com.jobs.core.exception.JobException;
import com.jobs.model.AbstractJob;
import com.jobs.model.TestJob;

public class JobFactory {
	private static JobFactory classInstance = new JobFactory();
	private Map<String, Job> jobMap = new HashMap<>();
	
	private JobFactory() {
		initializeJobMap();
	}
	public static JobFactory getInstance() {
		return classInstance;
	}
	
	private void initializeJobMap(){
		jobMap.put("TEST", new TestJob());
	}
	
	public void cacheJobInstance(Job jobInstance) throws JobInstanceReplacementException {
		if(jobInstance instanceof AbstractJob){
			AbstractJob absJob = (AbstractJob)jobInstance;
			if(!jobMap.containsKey(absJob.getJobName())){
				jobMap.put(absJob.getJobName(), absJob);
			}else{
				throw new JobInstanceReplacementException(jobInstance);
			}
		}
	}
	
	public Job getJob(String jobName){
		return jobMap.get(jobName.toUpperCase());
	}
	
	//Define all exceptions pumped out from this class
	public static final class JobInstanceReplacementException extends JobException {
		private static final long serialVersionUID = 1L;

		String customMessage;
		public JobInstanceReplacementException(Job jobInstance) {
			super("Job Instance already exists in the cache for the job name: "+ jobInstance.getJobName());			
		}
	}
}
